import {
  addPeople,
  updatePeople,
  updatePeopleRegion,
  getPeopleDetail,
  uploadPeoplePhoto,
  getPeoplePhotoUrl
} from '../../../utils/people'
import {
  getTempPeopleList
} from '../../../utils/temp_people'
import {
  splitAddress
} from '../../../utils/split_address'
import {
  getRegionTree,getSubRegion
} from '../../../utils/get_region'
var localInputCache = {};
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 'household', // 默认显示基本信息
    // 折叠状态，默认都展开
    showChildren: true,
    showGrandchildren: true,
    showExternalGrandchildren: true,
    showOthers: true,

    // 评定相关数据
    showEvaluation: false,
    evaluationType: 'householder', // 评定类型，默认为户主
    evaluationMemberType: '', // 成员类型（childrenList等）
    evaluationMemberIndex: -1, // 成员索引
    evaluationData: {
      toilet: '完全自理',
      eating: '完全自理',
      activity: '完全自理',
      dressing: '完全自理',
      bathing: '完全自理'
    },

    // 能力等级评定选项
    evaluationOptions: {
      toilet: ['完全自理', '部分自理', '完全不能自理'],
      eating: ['完全自理', '部分自理', '完全不能自理'],
      activity: ['完全自理', '部分自理', '完全不能自理'],
      dressing: ['完全自理', '部分自理', '完全不能自理'],
      bathing: ['完全自理', '部分自理', '完全不能自理']
    },

    // 生活自理能力选项
    selfCareAbilityList: ['完全自理', '部分自理', '完全不能自理'],

    // 医疗依赖类型选项
    medicalDependencyTypeList: ['无依赖', '低度依赖', '中度依赖', '高度依赖'],

    // 伤残等级选项
    disabilityLevelList: ['一级 (完全无法参与社会活动)', '二级 (严重受限，需全天监护)', '三级 (部分受限，需间歇支持)', '四级 (轻度受限，需部分支持)'],
    disabilityLevelIndex: 0,
    spouseDisabilityLevelIndex: 0,

    // 关系选项列表
    relationList: ['子女', '孙子女'],
    //家庭等级评定
    familyLevelList: ['红', '橙', '黄', '绿'],

    // 各个选择器的选项列表
    ethnicityList: ['汉族', '蒙古族', '回族', '藏族', '维吾尔族', '苗族', '彝族', '壮族', '布依族', '朝鲜族', '满族', '侗族', '瑶族', '白族', '土家族', '哈尼族', '哈萨克族', '傣族', '黎族', '傈僳族', '佤族', '畲族', '高山族', '拉祜族', '水族', '东乡族', '纳西族', '景颇族', '柯尔克孜族', '土族', '达斡尔族', '仫佬族', '羌族', '布朗族', '撒拉族', '毛南族', '仡佬族', '锡伯族', '阿昌族', '普米族', '塔吉克族', '怒族', '乌孜别克族', '俄罗斯族', '鄂温克族', '德昂族', '保安族', '裕固族', '京族', '塔塔尔族', '独龙族', '鄂伦春族', '赫哲族', '门巴族', '珞巴族', '基诺族'],
    ethnicityIndex: 0,
    politicalList: ['群众', '中共党员', '中共预备党员', '共青团员', '民革党员', '民盟盟员', '民建会员', '民进会员', '农工党党员', '致公党党员', '九三学社社员', '台盟盟员', '无党派人士'],
    politicalIndex: 0,
    maritalStatusList: ['未婚', '已婚', '丧偶', '离婚', '其他'],
    maritalStatusIndex: 0,
    educationList: ['文盲', '小学', '初中', '高中', '中专', '大专', '本科', '研究生', '博士及以上'],
    educationIndex: 0,
    workStatusList: ['无业', '单位职工', '离退休人员', '自由职业', '个体工商户', '学生', '务农', '其他'],
    workStatusIndex: 0,
    bloodTypeList: ['不详', 'A型', 'B型', 'AB型', 'O型', '其他'],
    bloodTypeIndex: 0,
    spouseBloodTypeIndex: 0,
    healthStatusList: ['良好', '一般', '较差', '死亡'],
    healthStatusIndex: 0,
    disabilityTypeList: ['无', '视力残疾', '听力残疾', '言语残疾', '肢体残疾', '智力残疾', '精神残疾', '多重残疾'],
    disabilityTypeIndex: 0,

    // 区域数据
    provinceList: [],
    cityList: [],
    districtList: [],
    streetList: [],
    provinceIndex: 0,
    cityIndex: 0,
    districtIndex: 0,
    streetIndex: 0,
    directCitySelected: false, // 是否选择了直辖市

    formData: {
      // 户主信息
      householder: {
        id: '', // 户主ID
        name: '', // 姓名
        relation: '户主', // 关系
        photoUrl: '', // 照片URL
        idNumber: '', // 身份证号
        address: '', // 户籍地址
        regionText: '', // 省市区文本
        detailAddress: '', // 详细地址
        currentRegionText: '', // 现住址省市区文本
        currentDetailAddress: '', // 现住址详细地址
        currentAddress: '', // 现住址完整地址
        gender: '男', // 性别
        birthday: '', // 出生年月
        ethnicity: '汉族', // 民族
        region: '城市', // 地域
        political: '群众', // 政治面貌
        maritalStatus: '未婚', // 婚姻状况
        education: '初中', // 文化程度
        phone: '', // 电话
        administrativeDivisions: '', // 行政区划
        adminRegionText: '', // 行政区划省市区文本
        remark: '', // 备注

        // 工作情况
        workUnit: '无', // 工作单位/学校
        workStatus: '无业', // 工作情况

        // 健康状况
        healthId: '', // 健康ID
        bloodType: '不详', // 血型
        limbsActivity: '自如', // 四肢活动
        medicalHistory: '', // 既往病史
        recordDisease: '', // 建档时疾病
        longTermMedication: '否', // 长期用药
        majorDiseases: '', // 重大疾病
        healthStatus: '良好', // 健康状况
        disabilityType: '无', // 伤残类别
        disabilityLevel: '无', // 伤残等级
        abilityLevel: '', // 能力评定结果
        healthremarks: '', // 健康备注

        // 社会保障
        socialSecurityId: '', // 社会保障ID
        medicalInfo: '', // 医疗
        pensionInfo: '', // 养老
        housingInfo: '', // 住房
        lowIncomeInfo: '', // 低保
        insuranceInfo: '', // 保险
        fiveGuaranteesInfo: '', // 五保
        otherInsuranceInfo: '', // 其他保障
        employmentSupportInfo: '', // 就业扶持
      },

      // 配偶信息
      spouse: {
        id: '', // 配偶ID
        name: '', // 姓名
        relation: '配偶', // 关系
        photoUrl: '', // 照片URL
        idNumber: '', // 身份证号
        address: '', // 户籍地址
        regionText: '', // 省市区文本
        detailAddress: '', // 详细地址
        currentRegionText: '', // 现住址省市区文本
        currentDetailAddress: '', // 现住址详细地址
        currentAddress: '', // 现住址完整地址
        gender: '女', // 性别
        birthday: '', // 出生年月
        ethnicity: '汉族', // 民族
        region: '城市', // 地域
        political: '群众', // 政治面貌
        maritalStatus: '已婚', // 婚姻状况
        education: '初中', // 文化程度
        phone: '', // 电话

        // 行政区划
        administrativeDivisions: '', // 行政区划
        adminRegionText: '', // 行政区划省市区文本
        remark: '', // 备注
        // 工作情况
        workUnit: '无', // 工作单位/学校
        workStatus: '无业', // 工作情况

        // 健康状况
        healthId: '', // 健康ID
        bloodType: '不详', // 血型
        limbsActivity: '自如', // 四肢活动
        medicalHistory: '', // 既往病史
        recordDisease: '', // 建档时疾病
        longTermMedication: '否', // 长期用药
        majorDiseases: '', // 重大疾病
        healthStatus: '良好', // 健康状况
        disabilityType: '无', // 伤残类别
        disabilityLevel: '无', // 伤残等级
        abilityLevel: '', // 能力评定结果
        healthremarks: '', // 健康备注

        // 社会保障
        socialSecurityId: '', // 社会保障ID
        medicalInfo: '', // 医疗
        pensionInfo: '', // 养老
        housingInfo: '', // 住房
        lowIncomeInfo: '', // 低保
        insuranceInfo: '', // 保险
        fiveGuaranteesInfo: '', // 五保
        otherInsuranceInfo: '', // 其他保障
        employmentSupportInfo: '', // 就业扶持
      },

      // 家庭情况
      familyLevel: '', // 家庭等级
      income: '', // 年收入
      expense: '', // 年支出

      // 行政区划
      province: '', // 省
      provinceCode: '', // 省代码
      city: '', // 市
      cityCode: '', // 市代码
      district: '', // 区/县
      districtCode: '', // 区/县代码
      street: '', // 街道
      streetCode: '', // 街道代码

      //要删除的成员ID
      deleteMemberId: [],

      // 成员信息（数组形式，支持多个子女）
      memberList: [{
        id: '', // 成员ID
        name: '', // 姓名
        relation: '', // 关系
        isAdopted: '否', // 是否收养
        gender: '男', // 性别
        birthday: '', // 出生日期
        healthStatus: '', // 健康状况
        selfCareAbility: '', // 生活自理能力
        isLivingAlone: '否', // 是否独居
        disabilityType: '无', // 伤残类别 
        disabilityLevel: '无', // 伤残等级
        medicalDependencyType: '', // 医疗依赖类型
        hasChronicDisease: '否', // 是否有慢性病
        chronicDiseaseName: '', // 慢性病名称
        regularMedication: '', // 常用药物
        abilityLevel: '', // 等级划分
        remarks: '' // 备注
      }],
    },

    // 下拉选择器数据
    spousePoliticalIndex: 0,
    spouseWorkStatusIndex: 0,
    spouseBloodTypeIndex: 0,
    spouseWorkStatusIndex: 0,
    bloodTypeIndex: 0,
    spouseBloodTypeIndex: 0,
    healthStatusIndex: 0,
    disabilityTypeIndex: 0,

    // 存储textarea高度的对象
    textareaHeight: {
      householder: {},
      spouse: {},
      memberList: []
    },

    // 搜索功能相关数据
    showSearch: false, // 是否显示搜索弹窗
    iosKeyboardActive: false, // iOS软键盘是否激活
    searchData: {
      name: '', // 搜索的姓名
      idNumber: '', // 搜索的身份证号
      region: '' // 搜索的地区
    },
    searchResults: [], // 搜索结果列表
    searchPerformed: false, // 是否已执行过搜索
  },

  /**
   * 切换左侧边栏
   */
  switchTab: function (e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });
  },

  /**
   * 处理户主输入框变化
   */
  inputChange: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    // const newData = {};
    localInputCache[`formData.householder.${field}`] = value;
    //身份证号长度为18位时转出生日期
    // if (field === 'idNumber' && value.length === 18) {
    //   const birthDate = value.slice(6, 10) + '-' + value.slice(10, 12) + '-' + value.slice(12, 14);
    //   localInputCache['formData.householder.birthday'] = birthDate;
    // }

    // // 如果是详细地址变化，需要拼接完整地址
    // if (field === 'detailAddress') {
    //   const regionText = this.data.formData.householder.regionText || '';
    //   const fullAddress = regionText + value;
    //   localInputCache['formData.householder.address'] = fullAddress;
    // }

    // // 如果是现住址详细地址变化，需要拼接完整现住址
    // if (field === 'currentDetailAddress') {
    //   const currentRegionText = this.data.formData.householder.currentRegionText || '';
    //   const fullCurrentAddress = currentRegionText + value;
    //   localInputCache['formData.householder.currentAddress'] = fullCurrentAddress;
    // }

    // this.setData(newData);

    // 如果是textarea，适应内容高度（通过自动设置行高）
    // if (e.currentTarget.dataset.type === 'textarea') {
    //   const lineHeight = 1.4;
    //   const padding = 16; // 上下padding总和
    //   const minHeight = 36;
    //   const lineCount = value.split('\n').length;
    //   let height = lineCount * lineHeight * 14 + padding; // 14是字体大小
    //   height = Math.max(height, minHeight);
    //   height = Math.min(height, 150); // 最大高度限制

    //   const heightData = {};
    //   heightData[`textareaHeight.householder.${field}`] = height + 'px';
    //   this.setData(heightData);
    // }
  },
  inputBlur: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = localInputCache[`formData.householder.${field}`];
    if (value) {
      //身份证号长度为18位时转出生日期
      if (field === 'idNumber' && value.length === 18) {
        const birthDate = value.slice(6, 10) + '-' + value.slice(10, 12) + '-' + value.slice(12, 14);
        localInputCache['formData.householder.birthday'] = birthDate;
      }

      // 如果是详细地址变化，需要拼接完整地址
      if (field === 'detailAddress') {
        const regionText = this.data.formData.householder.regionText || '';
        const fullAddress = regionText + value;
        localInputCache['formData.householder.address'] = fullAddress;
      }

      // 如果是现住址详细地址变化，需要拼接完整现住址
      if (field === 'currentDetailAddress') {
        const currentRegionText = this.data.formData.householder.currentRegionText || '';
        const fullCurrentAddress = currentRegionText + value;
        localInputCache['formData.householder.currentAddress'] = fullCurrentAddress;
      }
      // const newData = {};
      // newData[`formData.householder.${field}`] = value;
      this.setData(localInputCache);
      localInputCache = {};
    }
  },
  /**
   * 处理配偶输入框变化
   */
  spouseInputChange: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    // const newData = {};
    localInputCache[`formData.spouse.${field}`] = value;
    // //身份证号长度为18位时转出生日期
    // if (field === 'idNumber' && value.length === 18) {
    //   const birthDate = value.slice(6, 10) + '-' + value.slice(10, 12) + '-' + value.slice(12, 14);
    //   localInputCache['formData.spouse.birthday'] = birthDate;
    // }

    // // 如果是详细地址变化，需要拼接完整地址
    // if (field === 'detailAddress') {
    //   const regionText = this.data.formData.spouse.regionText || '';
    //   const fullAddress = regionText + value;
    //   localInputCache['formData.spouse.address'] = fullAddress;
    // }

    // // 如果是现住址详细地址变化，需要拼接完整现住址
    // if (field === 'currentDetailAddress') {
    //   const currentRegionText = this.data.formData.spouse.currentRegionText || '';
    //   const fullCurrentAddress = currentRegionText + value;
    //   localInputCache['formData.spouse.currentAddress'] = fullCurrentAddress;
    // }

    // this.setData(newData);

    // 如果是textarea，适应内容高度
    // if (e.currentTarget.dataset.type === 'textarea') {
    //   const lineHeight = 1.4;
    //   const padding = 16; // 上下padding总和
    //   const minHeight = 36;
    //   const lineCount = value.split('\n').length;
    //   let height = lineCount * lineHeight * 14 + padding; // 14是字体大小
    //   height = Math.max(height, minHeight);
    //   height = Math.min(height, 150); // 最大高度限制

    //   const heightData = {};
    //   heightData[`textareaHeight.spouse.${field}`] = height + 'px';
    //   this.setData(heightData);
    // }
  },
  spouseInputBlur: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = localInputCache[`formData.spouse.${field}`];
    //身份证号长度为18位时转出生日期
    console.log(value)
    if (value) {
      if (field === 'idNumber' && value.length === 18) {
        const birthDate = value.slice(6, 10) + '-' + value.slice(10, 12) + '-' + value.slice(12, 14);
        localInputCache['formData.spouse.birthday'] = birthDate;
      }

      // 如果是详细地址变化，需要拼接完整地址
      if (field === 'detailAddress') {
        const regionText = this.data.formData.spouse.regionText || '';
        const fullAddress = regionText + value;
        localInputCache['formData.spouse.address'] = fullAddress;
      }

      // 如果是现住址详细地址变化，需要拼接完整现住址
      if (field === 'currentDetailAddress') {
        const currentRegionText = this.data.formData.spouse.currentRegionText || '';
        const fullCurrentAddress = currentRegionText + value;
        localInputCache['formData.spouse.currentAddress'] = fullCurrentAddress;
      }
      // const newData = {};
      // newData[`formData.householder.${field}`] = value;
      this.setData(localInputCache);
      localInputCache = {};
    }
  },
  /**
   * 处理户主单选框变化
   */
  radioChange: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    const newData = {};
    newData[`formData.householder.${field}`] = value;
    this.setData(newData);
  },

  /**
   * 处理配偶单选框变化
   */
  spouseRadioChange: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    const newData = {};
    newData[`formData.spouse.${field}`] = value;
    this.setData(newData);
  },

  /**
   * 处理户主日期选择器变化
   */
  dateChange: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    const newData = {};
    newData[`formData.householder.${field}`] = value;
    this.setData(newData);
  },

  /**
   * 处理配偶日期选择器变化
   */
  spouseDateChange: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    const newData = {};
    newData[`formData.spouse.${field}`] = value;
    this.setData(newData);
  },

  /**
   * 处理户主选择器变化
   */
  pickerChange: function (e) {
    const {
      value
    } = e.detail;
    const {
      field
    } = e.currentTarget.dataset;

    if (field === 'ethnicity') {
      this.setData({
        'formData.householder.ethnicity': this.data.ethnicityList[value],
        ethnicityIndex: value
      });
    } else if (field === 'political') {
      this.setData({
        'formData.householder.political': this.data.politicalList[value],
        politicalIndex: value
      });
    } else if (field === 'maritalStatus') {
      this.setData({
        'formData.householder.maritalStatus': this.data.maritalStatusList[value],
        maritalStatusIndex: value
      });
    } else if (field === 'education') {
      this.setData({
        'formData.householder.education': this.data.educationList[value],
        educationIndex: value
      });
    } else if (field === 'workStatus') {
      if (this.data.workStatusList[value] === "无业" || this.data.workStatusList[value] === "务农") {
        this.setData({
          'formData.householder.workUnit': '无',
          'formData.householder.workStatus': this.data.workStatusList[value],
          workStatusIndex: value
        });
      } else {
        this.setData({
          'formData.householder.workUnit': '',
          'formData.householder.workStatus': this.data.workStatusList[value],
          workStatusIndex: value
        });
      }
    } else if (field === 'bloodType') {
      this.setData({
        'formData.householder.bloodType': this.data.bloodTypeList[value],
        bloodTypeIndex: value
      });
    } else if (field === 'healthStatus') {
      this.setData({
        'formData.householder.healthStatus': this.data.healthStatusList[value],
        healthStatusIndex: value
      });
    } else if (field === 'disabilityType') {
      this.setData({
        'formData.householder.disabilityType': this.data.disabilityTypeList[value],
        disabilityTypeIndex: value
      });
    } else if (field === 'disabilityLevel') {
      this.setData({
        'formData.householder.disabilityLevel': this.data.disabilityLevelList[value],
        disabilityLevelIndex: value
      });
    } else {
      const newData = {};
      newData[`formData.householder.${field}`] = value;
      this.setData(newData);
    }
  },

  /**
   * 处理配偶选择器变化
   */
  spousePickerChange: function (e) {
    const {
      value
    } = e.detail;
    const {
      field
    } = e.currentTarget.dataset;

    if (field === 'ethnicity') {
      this.setData({
        'formData.spouse.ethnicity': this.data.ethnicityList[value],
        spouseEthnicityIndex: value
      });
    } else if (field === 'political') {
      this.setData({
        'formData.spouse.political': this.data.politicalList[value],
        spousePoliticalIndex: value
      });
    } else if (field === 'maritalStatus') {
      this.setData({
        'formData.spouse.maritalStatus': this.data.maritalStatusList[value],
        spouseMaritalStatusIndex: value
      });
    } else if (field === 'education') {
      this.setData({
        'formData.spouse.education': this.data.educationList[value],
        spouseEducationIndex: value
      });
    } else if (field === 'workStatus') {
      if (this.data.workStatusList[value] === "无业" || this.data.workStatusList[value] === "务农") {
        this.setData({
          'formData.spouse.workUnit': '无',
          'formData.spouse.workStatus': this.data.workStatusList[value],
          spouseWorkStatusIndex: value
        });
      } else {
        this.setData({
          'formData.spouse.workUnit': '',
          'formData.spouse.workStatus': this.data.workStatusList[value],
          spouseWorkStatusIndex: value
        });
      }

    } else if (field === 'bloodType') {
      this.setData({
        'formData.spouse.bloodType': this.data.bloodTypeList[value],
        spouseBloodTypeIndex: value
      });
    } else if (field === 'healthStatus') {
      this.setData({
        'formData.spouse.healthStatus': this.data.healthStatusList[value],
        spouseHealthStatusIndex: value
      });
    } else if (field === 'disabilityType') {
      this.setData({
        'formData.spouse.disabilityType': this.data.disabilityTypeList[value],
        spouseDisabilityTypeIndex: value
      });
    } else if (field === 'disabilityLevel') {
      this.setData({
        'formData.spouse.disabilityLevel': this.data.disabilityLevelList[value],
        spouseDisabilityLevelIndex: value
      });
    } else if (field === 'abilityLevel') {
      this.setData({
        'formData.spouse.abilityLevel': this.data.abilityLevelList[value],
        spouseAbilityLevelIndex: value
      });
    } else {
      const newData = {};
      newData[`formData.spouse.${field}`] = value;
      this.setData(newData);
    }
  },

  /**
   * 处理户主户籍行政区划选择器变化
   */
  householderRegionChange: function (e) {
    const region = e.detail.value;
    const regionText = region[0] + region[1] + region[2];
    const detailAddress = this.data.formData.householder.detailAddress || '';

    // 拼接完整地址
    const fullAddress = regionText + detailAddress;

    this.setData({
      'formData.householder.regionText': regionText,
      'formData.householder.address': fullAddress,
      // 'formData.householder.administrativeDivisions': regionText
    });
  },

  /**
   * 处理户主现住址区域选择器变化
   */
  householderCurrentRegionChange: function (e) {
    const region = e.detail.value;
    const regionText = region[0] + region[1] + region[2];
    const detailAddress = this.data.formData.householder.currentDetailAddress || '';

    // 拼接完整现住址
    const fullAddress = regionText + detailAddress;

    this.setData({
      'formData.householder.currentRegionText': regionText,
      'formData.householder.currentAddress': fullAddress
    });
  },

  /**
   * 处理配偶户籍行政区划选择器变化
   */
  spouseRegionChange: function (e) {
    const region = e.detail.value;
    const regionText = region[0] + region[1] + region[2];
    const detailAddress = this.data.formData.spouse.detailAddress || '';

    // 拼接完整地址
    const fullAddress = regionText + detailAddress;

    this.setData({
      'formData.spouse.regionText': regionText,
      'formData.spouse.address': fullAddress,
      // 现住址默认与户籍地址相同
      // 'formData.spouse.currentRegionText': regionText,
      // 'formData.spouse.currentDetailAddress': detailAddress,
      // 'formData.spouse.currentAddress': fullAddress,
      // 'formData.spouse.gender': this.data.formData.spouse.gender,
      // 'formData.spouse.administrativeDivisions': regionText,
      // 'formData.spouse.adminRegionText': regionText,
      // 'formData.spouse.remark': this.data.formData.spouse.remark,
    });
  },

  /**
   * 处理配偶现住址区域选择器变化
   */
  spouseCurrentRegionChange: function (e) {
    const region = e.detail.value;
    const regionText = region[0] + region[1] + region[2];
    const detailAddress = this.data.formData.spouse.currentDetailAddress || '';

    // 拼接完整现住址
    const fullAddress = regionText + detailAddress;

    this.setData({
      'formData.spouse.currentRegionText': regionText,
      'formData.spouse.currentAddress': fullAddress
    });
  },

  /**
   * 处理家庭情况输入框变化
   */
  familyInfoInputChange: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    const newData = {};
    newData[`formData.${field}`] = value;
    this.setData(newData);
  },
  /**
   * 处理家庭等级选择器变化
   */
  familyLevelPickerChange: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    const newData = {};
    newData[`formData.${field}`] = this.data.familyLevelList[value];
    this.setData(newData);
  },
  /**
   * 处理家庭成员展开收起
   */
  toggleSection: function (e) {
    const type = e.currentTarget.dataset.type;
    if (type === 'children') {
      this.setData({
        showChildren: !this.data.showChildren
      });
    } else if (type === 'grandchildren') {
      this.setData({
        showGrandchildren: !this.data.showGrandchildren
      });
    } else if (type === 'externalGrandchildren') {
      this.setData({
        showExternalGrandchildren: !this.data.showExternalGrandchildren
      });
    } else if (type === 'others') {
      this.setData({
        showOthers: !this.data.showOthers
      });
    }
  },

  /**
   * 添加家庭成员
   */
  addMember: function () {
    // 获取当前成员列表
    const memberList = this.data.formData.memberList || [];

    // 创建新成员信息模板
    const newMember = {
      name: '', // 姓名
      relation: '', // 关系
      isAdopted: '否', // 是否收养
      gender: '男', // 性别
      birthday: '', // 出生日期
      healthStatus: '', // 健康状况
      selfCareAbility: '', // 生活自理能力
      isLivingAlone: '否', // 是否独居
      disabilityType: '', // 伤残类别 
      medicalDependencyType: '', // 医疗依赖类型
      hasChronicDisease: '否', // 是否有慢性病
      chronicDiseaseName: '', // 慢性病名称
      regularMedication: '', // 常用药物
      abilityLevel: '', // 等级划分
      remarks: '' // 备注
    };

    // 将新成员添加到列表中
    memberList.push(newMember);

    // 更新数据
    this.setData({
      'formData.memberList': memberList
    });
  },

  /**
   * 删除家庭成员
   */
  deleteMember: function (e) {

    const index = e.currentTarget.dataset.index;
    //获取要删除的成员ID
    const deleteMemberId = this.data.formData.memberList[index].id;
    //将要删除的成员ID添加到数组中
    this.data.formData.deleteMemberId.push(deleteMemberId);
    const memberList = this.data.formData.memberList;

    // 如果列表只有一个成员，清空信息而不删除
    if (memberList.length === 1) {
      const emptyMember = {
        name: '', // 姓名
        relation: '', // 关系
        isAdopted: '否', // 是否收养
        gender: '男', // 性别
        birthday: '', // 出生日期
        healthStatus: '', // 健康状况
        selfCareAbility: '', // 生活自理能力
        isLivingAlone: '否', // 是否独居
        disabilityType: '', // 伤残类别 
        medicalDependencyType: '', // 医疗依赖类型
        hasChronicDisease: '否', // 是否有慢性病
        chronicDiseaseName: '', // 慢性病名称
        regularMedication: '', // 常用药物
        abilityLevel: '', // 等级划分
        remarks: '' // 备注
      };

      this.setData({
        'formData.memberList[0]': emptyMember
      });
    } else {
      // 删除指定索引的成员
      memberList.splice(index, 1);

      this.setData({
        'formData.memberList': memberList
      });
    }
  },

  /**
   * 处理成员输入框变化
   */
  memberInputChange: function (e) {
    const {
      index,
      field
    } = e.currentTarget.dataset;
    const value = e.detail.value;
    const path = `formData.memberList[${index}].${field}`;
    const newData = {};
    newData[path] = value;
    this.setData(newData);

    // 如果是textarea，适应内容高度
    if (e.currentTarget.dataset.type === 'textarea') {
      const lineHeight = 1.4;
      const padding = 16; // 上下padding总和
      const minHeight = 36;
      const lineCount = value.split('\n').length;
      let height = lineCount * lineHeight * 14 + padding; // 14是字体大小
      height = Math.max(height, minHeight);
      height = Math.min(height, 150); // 最大高度限制

      const heightData = {};
      heightData[`textareaHeight.memberList[${index}].${field}`] = height + 'px';
      this.setData(heightData);
    }
  },

  /**
   * 处理成员单选框变化
   */
  memberRadioChange: function (e) {
    const {
      index,
      field
    } = e.currentTarget.dataset;
    const value = e.detail.value;
    const path = `formData.memberList[${index}].${field}`;
    const newData = {};
    newData[path] = value;
    // console.log(newData);
    this.setData(newData);
  },

  /**
   * 处理成员日期选择器变化
   */
  memberDateChange: function (e) {
    const {
      index,
      field
    } = e.currentTarget.dataset;
    const value = e.detail.value;
    const path = `formData.memberList[${index}].${field}`;
    const newData = {};
    newData[path] = value;
    this.setData(newData);
  },

  /**
   * 处理成员选择器变化
   */
  memberPickerChange: function (e) {
    const {
      index,
      field
    } = e.currentTarget.dataset;
    const value = e.detail.value;
    let selectedValue;

    if (field === 'healthStatus') {
      selectedValue = this.data.healthStatusList[value];
    } else if (field === 'selfCareAbility') {
      selectedValue = this.data.selfCareAbilityList[value];
    } else if (field === 'medicalDependencyType') {
      selectedValue = this.data.medicalDependencyTypeList[value];
    } else if (field === 'disabilityType') {
      selectedValue = this.data.disabilityTypeList[value];
      if (selectedValue === '无') {
        const path = `formData.memberList[${index}].disabilityLevel`;
        const newData = {};
        newData[path] = '无';
        this.setData(newData);
      }
    } else if (field === 'disabilityLevel') {
      selectedValue = this.data.disabilityLevelList[value];
    } else if (field === 'relation') {
      selectedValue = this.data.relationList[value];
    } else {
      selectedValue = value;
    }

    const path = `formData.memberList[${index}].${field}`;
    const newData = {};
    newData[path] = selectedValue;
    this.setData(newData);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 加载区域数据
    this.loadAreaData();

    // 如果有ID参数，说明是编辑模式
    if (options.id) {
      this.setData({
        editMode: true,
        peopleId: options.id
      });
      // 获取人员详情
      this.loadPeopleDetail(options.id);
    } else {
      // 初始化户主索引
      const defaultMaritalStatus = this.data.formData.householder.maritalStatus;
      const maritalStatusIndex = this.data.maritalStatusList.findIndex(item => item === defaultMaritalStatus);
      if (maritalStatusIndex !== -1) {
        this.setData({
          maritalStatusIndex
        });
      }

      const defaultEducation = this.data.formData.householder.education;
      const educationIndex = this.data.educationList.findIndex(item => item === defaultEducation);
      if (educationIndex !== -1) {
        this.setData({
          educationIndex
        });
      }

      const defaultWorkStatus = this.data.formData.householder.workStatus;
      const workStatusIndex = this.data.workStatusList.findIndex(item => item === defaultWorkStatus);
      if (workStatusIndex !== -1) {
        this.setData({
          workStatusIndex
        });
      }

      const defaultBloodType = this.data.formData.householder.bloodType;
      const bloodTypeIndex = this.data.bloodTypeList.findIndex(item => item === defaultBloodType);
      if (bloodTypeIndex !== -1) {
        this.setData({
          bloodTypeIndex
        });
      }

      const defaultHealthStatus = this.data.formData.householder.healthStatus;
      const healthStatusIndex = this.data.healthStatusList.findIndex(item => item === defaultHealthStatus);
      if (healthStatusIndex !== -1) {
        this.setData({
          healthStatusIndex
        });
      }

      const defaultDisabilityType = this.data.formData.householder.disabilityType;
      const disabilityTypeIndex = this.data.disabilityTypeList.findIndex(item => item === defaultDisabilityType);
      if (disabilityTypeIndex !== -1) {
        this.setData({
          disabilityTypeIndex
        });
      }

      // 初始化配偶索引
      const spouseDefaultBloodType = this.data.formData.spouse.bloodType;
      const spouseBloodTypeIndex = this.data.bloodTypeList.findIndex(item => item === spouseDefaultBloodType);
      if (spouseBloodTypeIndex !== -1) {
        this.setData({
          spouseBloodTypeIndex
        });
      }

      const spouseDefaultHealthStatus = this.data.formData.spouse.healthStatus;
      const spouseHealthStatusIndex = this.data.healthStatusList.findIndex(item => item === spouseDefaultHealthStatus);
      if (spouseHealthStatusIndex !== -1) {
        this.setData({
          spouseHealthStatusIndex
        });
      }

      const spouseDefaultDisabilityType = this.data.formData.spouse.disabilityType;
      const spouseDisabilityTypeIndex = this.data.disabilityTypeList.findIndex(item => item === spouseDefaultDisabilityType);
      if (spouseDisabilityTypeIndex !== -1) {
        this.setData({
          spouseDisabilityTypeIndex
        });
      }
    }
  },

  /**
   * 加载人员详细信息
   */
  loadPeopleDetail: function (id) {
    wx.showLoading({
      title: '加载中...',
    });

    getPeopleDetail(id).then(res => {

      const data = res.data
      console.log("家庭基本信息：",data);

      //拿出基本信息
      this.setData({
        'formData.id': data.uid,
        'formData.familyLevel': data.grading,
        'formData.income': data.annualIncome,
        'formData.expense': data.annualExpenditure,
        'formData.province': data.provinceName,
        'formData.provinceCode': data.provinceId,
        'formData.city': data.municipalityName,
        'formData.cityCode': data.municipalityId,
        'formData.district': data.districtName,
        'formData.districtCode': data.districtId,
        'formData.street': data.townshipStreetsName,
        'formData.streetCode': data.townshipStreetsId,
      })
      // //拿出本人信息
      const self = data.listHouseHoldSpouse.find(item => item.relation === '户主')
      if (self.photoUrl && self.photoUrl !== '无') {
        //获取户主照片
        getPeoplePhotoUrl({
          'photokey': self.photoUrl
        }).then(res => {
          this.setData({
            'formData.householder.photoUrl': res.data
          })
          // console.log(res);
        })
      }
      // //拿出配偶信息
      const spouse = data.listHouseHoldSpouse.find(item => item.relation === '配偶')
      if (spouse && spouse.photoUrl && spouse.photoUrl !== '无') {
        //获取配偶照片
        getPeoplePhotoUrl({
          'photokey': spouse.photoUrl
        }).then(res => {
          this.setData({
            'formData.spouse.photoUrl': res.data
          })
          // console.log(res);
        })
      }
      //设置户主信息
      // 解析户主户籍信息
      const householdRegistLocation = self.householdRegistLocation || '';
      const householdRegistLocationArray = splitAddress(householdRegistLocation)
      // console.log("户主户籍信息：",householdRegistLocationArray);
      // 解析户主现住址信息
      const currentPlace = self.currentPlace || '';
      const currentPlaceArray = splitAddress(currentPlace)
      // console.log("户主现住址信息：",currentPlaceArray);
      // 解析户主行政区划信息
      const administrativeDivision = self.administrativeDivision || '';
      // const administrativeDivisionArray = splitAddress(administrativeDivision)

      this.setData({
        'formData.householder.id': self.uid,
        'formData.householder.name': self.name,
        'formData.householder.relation': self.relation,
        // 'formData.householder.photoUrl': self.photoUrl,
        'formData.householder.idNumber': self.identificationNumber,
        'formData.householder.address': householdRegistLocation,
        'formData.householder.regionText': householdRegistLocationArray[0],
        'formData.householder.detailAddress': householdRegistLocationArray[1],
        'formData.householder.currentRegionText': currentPlaceArray[0],
        'formData.householder.currentDetailAddress': currentPlaceArray[1],
        'formData.householder.currentAddress': currentPlace,
        'formData.householder.gender': self.gender,
        //只保留年月日
        'formData.householder.birthday': self.birthDate.split('T')[0],
        'formData.householder.ethnicity': self.ethnicity,
        'formData.householder.region': self.region,
        'formData.householder.political': self.politicalAffiliation,
        'formData.householder.maritalStatus': self.maritalStatus,
        'formData.householder.education': self.educationLevel,
        'formData.householder.phone': self.phoneNumber,
        'formData.householder.administrativeDivisions': self.administrativeDivision,
        'formData.householder.adminRegionText': self.administrativeDivision,
        'formData.householder.remark': self.remark,
        'formData.householder.workUnit': self.employerSchool,
        'formData.householder.workStatus': self.employmentStatus,
        'formData.householder.abilityLevel': self.grading,
        //健康状况
        'formData.householder.healthId': self.healthInformation.uid,
        'formData.householder.bloodType': self.healthInformation.bloodType,
        'formData.householder.limbsActivity': self.healthInformation.limbMobility,
        'formData.householder.medicalHistory': self.healthInformation.medicalHistory,
        'formData.householder.recordDisease': self.healthInformation.recordDisease,
        'formData.householder.longTermMedication': self.healthInformation.isLongTermMedication,
        'formData.householder.majorDiseases': self.healthInformation.majorDiseases,
        'formData.householder.healthStatus': self.healthInformation.healthStatus,
        'formData.householder.disabilityType': self.healthInformation.disabilityType,
        'formData.householder.disabilityLevel': self.healthInformation.disabilityLevel,
        'formData.householder.healthremarks': self.healthInformation.remark,
        //社会保障
        'formData.householder.socialSecurityId': self.socialSecurityInformation.uid,
        'formData.householder.medicalInfo': self.socialSecurityInformation.medicalInsurance,
        'formData.householder.pensionInfo': self.socialSecurityInformation.pensionInsurance,
        'formData.householder.housingInfo': self.socialSecurityInformation.housingFund,
        'formData.householder.lowIncomeInfo': self.socialSecurityInformation.lowIncomeSupport,
        'formData.householder.insuranceInfo': self.socialSecurityInformation.insurance,
        'formData.householder.fiveGuaranteesInfo': self.socialSecurityInformation.fiveGuaranteesSupport,
        'formData.householder.otherInsuranceInfo': self.socialSecurityInformation.otherBenefits,
        'formData.householder.employmentSupportInfo': self.socialSecurityInformation.employmentSupport,
      })
      //设置配偶信息
      if (spouse) {
        // 解析地址信息

        const spouseRegistLocation = spouse.householdRegistLocation || '';
        const spouseRegistLocationArray = splitAddress(spouseRegistLocation)
        // 解析配偶现住址信息
        const currentPlace = spouse.currentPlace || '';
        const currentPlaceArray = splitAddress(currentPlace)
        // 解析户主行政区划信息
        const administrativeDivision = spouse.administrativeDivision || '';
        const administrativeDivisionArray = splitAddress(administrativeDivision)


        //设置配偶信息
        this.setData({
          'formData.spouse.id': spouse.uid,
          'formData.spouse.name': spouse.name,
          'formData.spouse.relation': spouse.relation,
          // 'formData.spouse.photoUrl': spouse.photoUrl,
          'formData.spouse.idNumber': spouse.identificationNumber,
          'formData.spouse.address': spouseRegistLocation,
          'formData.spouse.regionText': spouseRegistLocationArray[0],
          'formData.spouse.detailAddress': spouseRegistLocationArray[1],
          // 现住址默认与户籍地址相同
          'formData.spouse.currentRegionText': currentPlaceArray[0],
          'formData.spouse.currentDetailAddress': currentPlaceArray[1],
          'formData.spouse.currentAddress': currentPlace,
          'formData.spouse.gender': spouse.gender,
          //只保留年月日
          'formData.spouse.birthday': spouse.birthDate.split('T')[0],
          'formData.spouse.ethnicity': spouse.ethnicity,
          'formData.spouse.region': spouse.region,
          'formData.spouse.political': spouse.politicalAffiliation,
          'formData.spouse.maritalStatus': spouse.maritalStatus,
          'formData.spouse.education': spouse.educationLevel,
          'formData.spouse.phone': spouse.phoneNumber,
          'formData.spouse.administrativeDivisions': spouse.administrativeDivision,
          'formData.spouse.adminRegionText': spouse.administrativeDivision,
          'formData.spouse.remark': spouse.remark,
          'formData.spouse.workUnit': spouse.employerSchool,
          'formData.spouse.workStatus': spouse.employmentStatus,
          'formData.spouse.abilityLevel': spouse.grading,
          //健康状况
          'formData.spouse.healthId': spouse.healthInformation.uid,
          'formData.spouse.bloodType': spouse.healthInformation.bloodType,
          'formData.spouse.limbsActivity': spouse.healthInformation.limbMobility,
          'formData.spouse.medicalHistory': spouse.healthInformation.medicalHistory,
          'formData.spouse.recordDisease': spouse.healthInformation.recordDisease,
          'formData.spouse.longTermMedication': spouse.healthInformation.isLongTermMedication,
          'formData.spouse.majorDiseases': spouse.healthInformation.majorDiseases,
          'formData.spouse.healthStatus': spouse.healthInformation.healthStatus,
          'formData.spouse.disabilityType': spouse.healthInformation.disabilityType,
          'formData.spouse.disabilityLevel': spouse.healthInformation.disabilityLevel,
          'formData.spouse.healthremarks': spouse.healthInformation.remark,
          //社会保障
          'formData.spouse.socialSecurityId': spouse.socialSecurityInformation.uid,
          'formData.spouse.medicalInfo': spouse.socialSecurityInformation.medicalInsurance,
          'formData.spouse.pensionInfo': spouse.socialSecurityInformation.pensionInsurance,
          'formData.spouse.housingInfo': spouse.socialSecurityInformation.housingFund,
          'formData.spouse.lowIncomeInfo': spouse.socialSecurityInformation.lowIncomeSupport,
          'formData.spouse.insuranceInfo': spouse.socialSecurityInformation.insurance,
          'formData.spouse.fiveGuaranteesInfo': spouse.socialSecurityInformation.fiveGuaranteesSupport,
          'formData.spouse.otherInsuranceInfo': spouse.socialSecurityInformation.otherBenefits,
          'formData.spouse.employmentSupportInfo': spouse.socialSecurityInformation.employmentSupport,
        })
      }
      //拿出子女信息
      const memberList = data.listChildGrand
      if (memberList.length > 0) {
        for (let i = 0; i < memberList.length; i++) {
          const member = memberList[i]
          let dataObj = {};
          dataObj[`formData.memberList[${i}].id`] = member.uid;
          dataObj[`formData.memberList[${i}].name`] = member.name;
          dataObj[`formData.memberList[${i}].relation`] = member.relation;
          dataObj[`formData.memberList[${i}].isAdopted`] = member.ifAdopt;
          dataObj[`formData.memberList[${i}].gender`] = member.gender;
          //只保留年月日
          dataObj[`formData.memberList[${i}].birthday`] = member.birthDate.split('T')[0];
          dataObj[`formData.memberList[${i}].healthStatus`] = member.healthStatus;
          dataObj[`formData.memberList[${i}].selfCareAbility`] = member.takecareLifeAbility;
          dataObj[`formData.memberList[${i}].isLivingAlone`] = member.ifLivingAlone;
          dataObj[`formData.memberList[${i}].disabilityType`] = member.disabilityType;
          dataObj[`formData.memberList[${i}].disabilityLevel`] = member.disabilityLevel;
          dataObj[`formData.memberList[${i}].medicalDependencyType`] = member.medicalDependence;
          dataObj[`formData.memberList[${i}].hasChronicDisease`] = member.ifChronicDisease;
          dataObj[`formData.memberList[${i}].chronicDiseaseName`] = member.chronicDiseaseName;
          dataObj[`formData.memberList[${i}].regularMedication`] = member.commonlyMedications;
          dataObj[`formData.memberList[${i}].abilityLevel`] = member.grading;
          dataObj[`formData.memberList[${i}].remarks`] = member.remark;
          this.setData(dataObj);
        }
      }
      // console.log(this.data.formData)
      wx.hideLoading();
    }).catch(err => {
      console.error('获取人员详情失败', err);
      wx.hideLoading();
      wx.showToast({
        title: '获取数据失败',
        icon: 'none',
        duration: 2000
      });
    });
  },

  /**
   * 提交表单
   */
  submitForm: function () {
    //验证必填字段
    if (!this.validateForm()) {
      return;
    }

    //如果是更新模式
    if (this.data.editMode) {
      //户主
      const householder = {
        'Uid': this.data.formData.householder.id,
        "Relation": this.data.formData.householder.relation,
        "Name": this.data.formData.householder.name,
        "IdentificationNumber": this.data.formData.householder.idNumber,
        "HouseholdRegistLocation": this.data.formData.householder.address,
        "CurrentPlace": this.data.formData.householder.currentAddress,
        "Gender": this.data.formData.householder.gender,
        "BirthDate": this.data.formData.householder.birthday,
        "Ethnicity": this.data.formData.householder.ethnicity,
        "Region": this.data.formData.householder.region,
        "PoliticalAffiliation": this.data.formData.householder.political,
        "MaritalStatus": this.data.formData.householder.maritalStatus,
        "EducationLevel": this.data.formData.householder.education,
        "PhoneNumber": this.data.formData.householder.phone,
        "AdministrativeDivision": this.data.formData.householder.administrativeDivisions,
        "EmployerSchool": this.data.formData.householder.workUnit,
        "EmploymentStatus": this.data.formData.householder.workStatus,
        "Remark": this.data.formData.householder.remark || '无',
        "Grading": this.data.formData.householder.abilityLevel,
        "UpdateHealthInformationRequest": {
          "BloodType": this.data.formData.householder.bloodType,
          "LimbMobility": this.data.formData.householder.limbsActivity,
          "MedicalHistory": this.data.formData.householder.medicalHistory,
          "RecordDisease": this.data.formData.householder.recordDisease,
          "IsLongTermMedication": this.data.formData.householder.longTermMedication,
          "MajorDiseases": this.data.formData.householder.majorDiseases,
          "HealthStatus": this.data.formData.householder.healthStatus,
          "DisabilityLevel": this.data.formData.householder.disabilityLevel,
          "DisabilityType": this.data.formData.householder.disabilityType,
          "Remark": this.data.formData.householder.healthremarks
        },
        "UpdateSocialSecurityRequest": {
          "MedicalInsurance": this.data.formData.householder.medicalInfo,
          "PensionInsurance": this.data.formData.householder.pensionInfo,
          "HousingFund": this.data.formData.householder.housingInfo,
          "LowIncomeSupport": this.data.formData.householder.lowIncomeInfo,
          "Insurance": this.data.formData.householder.insuranceInfo,
          "FiveGuaranteesSupport": this.data.formData.householder.fiveGuaranteesInfo,
          "OtherBenefits": this.data.formData.householder.otherInsuranceInfo,
          "EmploymentSupport": this.data.formData.householder.employmentSupportInfo
        }
      }
      //配偶
      const spouse = {
        'Uid': this.data.formData.spouse.id,
        "Relation": this.data.formData.spouse.relation,
        "Name": this.data.formData.spouse.name,
        "IdentificationNumber": this.data.formData.spouse.idNumber,
        "HouseholdRegistLocation": this.data.formData.spouse.address,
        "CurrentPlace": this.data.formData.spouse.currentAddress,
        "Gender": this.data.formData.spouse.gender,
        "BirthDate": this.data.formData.spouse.birthday,
        "Ethnicity": this.data.formData.spouse.ethnicity,
        "Region": this.data.formData.spouse.region,
        "PoliticalAffiliation": this.data.formData.spouse.political,
        "MaritalStatus": this.data.formData.spouse.maritalStatus,
        "EducationLevel": this.data.formData.spouse.education,
        "PhoneNumber": this.data.formData.spouse.phone,
        "AdministrativeDivision": this.data.formData.spouse.administrativeDivisions,
        "EmployerSchool": this.data.formData.spouse.workUnit,
        "EmploymentStatus": this.data.formData.spouse.workStatus,
        "Remark": this.data.formData.spouse.remark || '无',
        "Grading": this.data.formData.spouse.abilityLevel,
        "UpdateHealthInformationRequest": {
          "BloodType": this.data.formData.spouse.bloodType,
          "LimbMobility": this.data.formData.spouse.limbsActivity,
          "MedicalHistory": this.data.formData.spouse.medicalHistory,
          "RecordDisease": this.data.formData.spouse.recordDisease,
          "IsLongTermMedication": this.data.formData.spouse.longTermMedication,
          "MajorDiseases": this.data.formData.spouse.majorDiseases,
          "HealthStatus": this.data.formData.spouse.healthStatus,
          "DisabilityLevel": this.data.formData.spouse.disabilityLevel,
          "DisabilityType": this.data.formData.spouse.disabilityType,
          "Remark": this.data.formData.spouse.healthremarks
        },
        "UpdateSocialSecurityRequest": {
          "MedicalInsurance": this.data.formData.spouse.medicalInfo,
          "PensionInsurance": this.data.formData.spouse.pensionInfo,
          "HousingFund": this.data.formData.spouse.housingInfo,
          "LowIncomeSupport": this.data.formData.spouse.lowIncomeInfo,
          "Insurance": this.data.formData.spouse.insuranceInfo,
          "FiveGuaranteesSupport": this.data.formData.spouse.fiveGuaranteesInfo,
          "OtherBenefits": this.data.formData.spouse.otherInsuranceInfo,
          "EmploymentSupport": this.data.formData.spouse.employmentSupportInfo
        }
      }
      let householderSpouseList = [];
      //判断配偶是否为空
      if (spouse.Name) {
        householderSpouseList = [householder, spouse];
      } else {
        householderSpouseList = [householder];
      }
      //构造成员数组
      const memberList = this.data.formData.memberList;
      const memberDataList = [];
      for (let i = 0; i < memberList.length; i++) {
        //判断是否为空
        if (memberList[i].name) {
          const member = memberList[i];
          const memberData = {
            "Uid": member.id,
            "Name": member.name,
            "Relation": member.relation,
            "IfAdopt": member.isAdopted,
            "Gender": member.gender,
            "BirthDate": member.birthday,
            "HealthStatus": member.healthStatus,
            "TakecareLifeAbility": member.selfCareAbility,
            "IfLivingAlone": member.isLivingAlone,
            "DisabilityType": member.disabilityType,
            "DisabilityLevel": member.disabilityLevel,
            "MedicalDependence": member.medicalDependencyType,
            "IfChronicDisease": member.hasChronicDisease,
            "ChronicDiseaseName": member.chronicDiseaseName,
            "CommonlyMedications": member.regularMedication,
            "Grading": member.abilityLevel,
            "Remark": member.remarks
          }
          memberDataList.push(memberData);
        }
      }
      // 构建提交到服务器的数据结构
      const submitData = {
        "Grading": this.data.formData.familyLevel,
        "AnnualIncome": this.data.formData.income,
        "AnnualExpenditure": this.data.formData.expense,
        "FromProvinceId": this.data.formData.provinceCode,
        "FromProvinceName": this.data.formData.province,
        "FromMunicipalityId": this.data.formData.cityCode,
        "FromMunicipalityName": this.data.formData.city,
        "FromDistrictId": this.data.formData.districtCode,
        "FromDistrictName": this.data.formData.district,
        "FromTownshipStreetsId": this.data.formData.streetCode,
        "FromTownshipStreetsName": this.data.formData.street,
        'DeleteChildGrandUids': this.data.formData.deleteMemberId,
        "Remark": '无',
        "ListUpdateHouseHoldSpouseRequest": householderSpouseList,
        "ListUpdateChildGrandRequest": memberDataList
      };

      console.log('表单数据', submitData);
      //构造更新的行政区划数据
      const updateRegionData = {
        "FamilyId": this.data.formData.id,
        "ProvinceId": this.data.formData.provinceCode,
        "ProvinceName": this.data.formData.province,
        "MunicipalityId": this.data.formData.cityCode,
        "MunicipalityName": this.data.formData.city,
        "DistrictId": this.data.formData.districtCode,
        "DistrictName": this.data.formData.district,
        "TownshipStreetsId": this.data.formData.streetCode,
        "TownshipStreetsName": this.data.formData.street
      };

      submitData.Uid = this.data.formData.id;

      // 上传户主照片
      if (this.data.formData.householder.photoUrl) {
        // 检查文件是否为URL地址(以http开头)
        if (this.data.formData.householder.photoUrl.indexOf('https') !== 0) {
          // 如果不是http开头，说明是本地文件，需要检查文件是否存在
          wx.getFileInfo({
            filePath: this.data.formData.householder.photoUrl,
            success: (fileInfo) => {
              // 文件存在，可以上传
              const data = {
                'Uid': this.data.formData.householder.id,
                'File': this.data.formData.householder.photoUrl
              }
              uploadPeoplePhoto(data).then(res => {
                console.log('户主照片上传成功', res);
              }).catch(err => {
                console.error('户主照片上传失败', err);
                wx.showToast({
                  title: '户主照片上传失败',
                  icon: 'none',
                  duration: 2000
                });
              });
            },
            fail: (error) => {
              console.error('户主照片文件不存在', error);
              wx.showToast({
                title: '户主照片文件不存在',
                icon: 'none',
                duration: 2000
              });
            }
          });
        }
      }

      // 上传配偶照片
      if (this.data.formData.spouse.photoUrl) {
        // 检查文件是否为URL地址(以http开头)
        if (this.data.formData.spouse.photoUrl.indexOf('https') !== 0) {
          // 如果不是http开头，说明是本地文件，需要检查文件是否存在
          wx.getFileInfo({
            filePath: this.data.formData.spouse.photoUrl,
            success: (fileInfo) => {
              // 文件存在，可以上传
              const data = {
                'Uid': this.data.formData.spouse.id,
                'File': this.data.formData.spouse.photoUrl
              }
              uploadPeoplePhoto(data).then(res => {
                console.log('配偶照片上传成功', res);
              }).catch(err => {
                console.error('配偶照片上传失败', err);
                wx.showToast({
                  title: '配偶照片上传失败',
                  icon: 'none',
                  duration: 2000
                });
              });
            },
            fail: (error) => {
              console.error('配偶照片文件不存在', error);
              wx.showToast({
                title: '配偶照片文件不存在',
                icon: 'none',
                duration: 2000
              });
            }
          });
        }
      }

      //调用更新接口
      wx.showLoading()
      updatePeople(submitData).then(res => {
        // console.log(res);
        if (res.code === 200) {
          //更新行政区划信息
          updatePeopleRegion(updateRegionData).then(regionRes => {
            console.log('更新行政区划成功', regionRes);
          }).catch(regionErr => {
            console.error('更新行政区划失败', regionErr);
          });
          //跳转到人员列表
          setTimeout(() => {
            wx.hideLoading()
          }, 1000)
          // 修改这里：使用回调函数确保提示显示完成后再跳转
          wx.showToast({
            title: '更新成功',
            icon: 'success',
            duration: 1000,
            success: () => {
              // 当提示框成功显示完成后，会执行这个回调函数
              setTimeout(() => {
                // 跳转到人员列表
                wx.navigateBack()
              }, 1000); // 等待提示框显示的时间
            }
          });
        } else {
          setTimeout(() => {
            wx.hideLoading()
            wx.showToast({
              title: '更新失败',
              icon: 'none',
              duration: 1000
            });
          }, 1000)
        }
      }).catch(err => {
        console.error('更新人员失败', err);
        wx.hideLoading()
        wx.showToast({
          title: '更新失败',
          icon: 'none',
          duration: 1000
        });
      });
    } else {
      //户主
      const householder = {
        "Relation": this.data.formData.householder.relation,
        "Name": this.data.formData.householder.name,
        "IdentificationNumber": this.data.formData.householder.idNumber,
        "HouseholdRegistLocation": this.data.formData.householder.address,
        "CurrentPlace": this.data.formData.householder.currentAddress,
        "Gender": this.data.formData.householder.gender,
        "BirthDate": this.data.formData.householder.birthday,
        "Ethnicity": this.data.formData.householder.ethnicity,
        "Region": this.data.formData.householder.region,
        "PoliticalAffiliation": this.data.formData.householder.political,
        "MaritalStatus": this.data.formData.householder.maritalStatus,
        "EducationLevel": this.data.formData.householder.education,
        "PhoneNumber": this.data.formData.householder.phone,
        "AdministrativeDivision": this.data.formData.householder.administrativeDivisions,
        "EmployerSchool": this.data.formData.householder.workUnit,
        "EmploymentStatus": this.data.formData.householder.workStatus,
        "Remark": this.data.formData.householder.remark || '无',
        "Grading": this.data.formData.householder.abilityLevel,
        "HealthInformationRequest": {
          "BloodType": this.data.formData.householder.bloodType,
          "LimbMobility": this.data.formData.householder.limbsActivity,
          "MedicalHistory": this.data.formData.householder.medicalHistory,
          "RecordDisease": this.data.formData.householder.recordDisease,
          "IsLongTermMedication": this.data.formData.householder.longTermMedication,
          "MajorDiseases": this.data.formData.householder.majorDiseases,
          "HealthStatus": this.data.formData.householder.healthStatus,
          "DisabilityLevel": this.data.formData.householder.disabilityLevel,
          "DisabilityType": this.data.formData.householder.disabilityType,
          "Remark": this.data.formData.householder.healthremarks
        },
        "SocialSecurityRequest": {
          "MedicalInsurance": this.data.formData.householder.medicalInfo,
          "PensionInsurance": this.data.formData.householder.pensionInfo,
          "HousingFund": this.data.formData.householder.housingInfo,
          "LowIncomeSupport": this.data.formData.householder.lowIncomeInfo,
          "Insurance": this.data.formData.householder.insuranceInfo,
          "FiveGuaranteesSupport": this.data.formData.householder.fiveGuaranteesInfo,
          "OtherBenefits": this.data.formData.householder.otherInsuranceInfo,
          "EmploymentSupport": this.data.formData.householder.employmentSupportInfo
        }
      }
      //配偶
      const spouse = {
        "Relation": this.data.formData.spouse.relation,
        "Name": this.data.formData.spouse.name,
        "IdentificationNumber": this.data.formData.spouse.idNumber,
        "HouseholdRegistLocation": this.data.formData.spouse.address,
        "CurrentPlace": this.data.formData.spouse.currentAddress,
        "Gender": this.data.formData.spouse.gender,
        "BirthDate": this.data.formData.spouse.birthday,
        "Ethnicity": this.data.formData.spouse.ethnicity,
        "Region": this.data.formData.spouse.region,
        "PoliticalAffiliation": this.data.formData.spouse.political,
        "MaritalStatus": this.data.formData.spouse.maritalStatus,
        "EducationLevel": this.data.formData.spouse.education,
        "PhoneNumber": this.data.formData.spouse.phone,
        "AdministrativeDivision": this.data.formData.spouse.administrativeDivisions,
        "EmployerSchool": this.data.formData.spouse.workUnit,
        "EmploymentStatus": this.data.formData.spouse.workStatus,
        "Remark": this.data.formData.spouse.remark || '无',
        "Grading": this.data.formData.spouse.abilityLevel,
        "HealthInformationRequest": {
          "BloodType": this.data.formData.spouse.bloodType,
          "LimbMobility": this.data.formData.spouse.limbsActivity,
          "MedicalHistory": this.data.formData.spouse.medicalHistory,
          "RecordDisease": this.data.formData.spouse.recordDisease,
          "IsLongTermMedication": this.data.formData.spouse.longTermMedication,
          "MajorDiseases": this.data.formData.spouse.majorDiseases,
          "HealthStatus": this.data.formData.spouse.healthStatus,
          "DisabilityLevel": this.data.formData.spouse.disabilityLevel,
          "DisabilityType": this.data.formData.spouse.disabilityType,
          "Remark": this.data.formData.spouse.healthremarks
        },
        "SocialSecurityRequest": {
          "MedicalInsurance": this.data.formData.spouse.medicalInfo,
          "PensionInsurance": this.data.formData.spouse.pensionInfo,
          "HousingFund": this.data.formData.spouse.housingInfo,
          "LowIncomeSupport": this.data.formData.spouse.lowIncomeInfo,
          "Insurance": this.data.formData.spouse.insuranceInfo,
          "FiveGuaranteesSupport": this.data.formData.spouse.fiveGuaranteesInfo,
          "OtherBenefits": this.data.formData.spouse.otherInsuranceInfo,
          "EmploymentSupport": this.data.formData.spouse.employmentSupportInfo
        }
      }
      let householderSpouseList = [];
      //判断配偶是否为空
      if (spouse.Name) {
        householderSpouseList = [householder, spouse];
      } else {
        householderSpouseList = [householder];
      }
      //构造成员数组
      const memberList = this.data.formData.memberList;
      const memberDataList = [];
      for (let i = 0; i < memberList.length; i++) {
        //判断是否为空
        if (memberList[i].name) {
          const member = memberList[i];
          const memberData = {
            "Name": member.name,
            "Relation": member.relation,
            "IfAdopt": member.isAdopted,
            "Gender": member.gender,
            "BirthDate": member.birthday,
            "HealthStatus": member.healthStatus,
            "TakecareLifeAbility": member.selfCareAbility,
            "IfLivingAlone": member.isLivingAlone,
            "DisabilityType": member.disabilityType,
            "DisabilityLevel": member.disabilityLevel,
            "MedicalDependence": member.medicalDependencyType,
            "IfChronicDisease": member.hasChronicDisease,
            "ChronicDiseaseName": member.chronicDiseaseName,
            "CommonlyMedications": member.regularMedication,
            "Grading": member.abilityLevel,
            "Remark": member.remarks
          }
          memberDataList.push(memberData);
        }
      }

      // 构建提交到服务器的数据结构
      const submitData = {
        "Grading": this.data.formData.familyLevel,
        "AnnualIncome": this.data.formData.income,
        "AnnualExpenditure": this.data.formData.expense,
        "ProvinceId": this.data.formData.provinceCode,
        "ProvinceName": this.data.formData.province,
        "MunicipalityId": this.data.formData.cityCode,
        "MunicipalityName": this.data.formData.city,
        "DistrictId": this.data.formData.districtCode,
        "DistrictName": this.data.formData.district,
        "TownshipStreetsId": this.data.formData.streetCode,
        "TownshipStreetsName": this.data.formData.street,
        "Remark": '无',
        "ListEnrollHouseHoldSpouseRequest": householderSpouseList,
        "ListEnrollChildGrandRequest": memberDataList
      };

      // console.log('表单数据', submitData);
      // console.log('所有数据', this.data.formData);
      //调用添加接口
      wx.showLoading()
      addPeople(submitData).then(res => {
        // console.log(res);
        if (res.code === 200) {
          // console.log(res.data);
          setTimeout(() => {
            wx.hideLoading()
          }, 1000)

          // 修改这里：使用回调函数确保提示显示完成后再跳转
          wx.showToast({
            title: '添加成功',
            icon: 'success',
            duration: 1000,
            success: () => {
              // 当提示框成功显示完成后，会执行这个回调函数
              setTimeout(() => {
                // 跳转到人员列表
                wx.navigateBack()
              }, 1000); // 等待提示框显示的时间
            }
          });
        } else {
          setTimeout(() => {
            wx.hideLoading()
            wx.showToast({
              title: res.message,
              icon: 'none',
              duration: 2000
            });
          }, 1000)
        }
      }).catch(err => {
        wx.hideLoading()
        setTimeout(() => {
          wx.showToast({
            title: '添加失败',
            icon: 'none',
            duration: 2000
          });
        }, 1000)
      });
    }
  },

  /**
   * 验证表单
   */
  validateForm: function () {
    const householder = this.data.formData.householder;
    const reg = /(^\d{15}$)|(^\d{17}(\d|X|x)$)/;


    if (!householder.name) {
      wx.showToast({
        title: '请填写户主姓名',
        icon: 'none'
      });
      return false;
    }

    if (!householder.idNumber) {
      wx.showToast({
        title: '请填写户主身份证号',
        icon: 'none'
      });
      return false;
    }
    if (!reg.test(householder.idNumber)) {
      wx.showToast({
        title: '户主身份证号格式不正确',
        icon: 'none'
      });
      return false;
    }

    if (!householder.address) {
      wx.showToast({
        title: '请填写户主户籍地址',
        icon: 'none'
      });
      return false;
    }
    if (!householder.currentAddress) {
      wx.showToast({
        title: '请填写户主现住地址',
        icon: 'none'
      });
      return false;
    }
    //性别
    if (!householder.gender) {
      wx.showToast({
        title: '请选择户主性别',
        icon: 'none'
      });
      return false;
    }
    //出生日期
    if (!householder.birthday) {
      wx.showToast({
        title: '请填写户主出生日期',
        icon: 'none'
      });
      return false;
    }
    //民族
    if (!householder.ethnicity) {
      wx.showToast({
        title: '请选择户主民族',
        icon: 'none'
      });
      return false;
    }
    //地域
    if (!householder.region) {
      wx.showToast({
        title: '请选择户主地域',
        icon: 'none'
      });
      return false;
    }
    //政治面貌
    if (!householder.political) {
      wx.showToast({
        title: '请选择户主政治面貌',
        icon: 'none'
      });
      return false;
    }
    //婚姻状况
    if (!householder.maritalStatus) {
      wx.showToast({
        title: '请选择户主婚姻状况',
        icon: 'none'
      });
      return false;
    }
    //文化程度
    if (!householder.education) {
      wx.showToast({
        title: '请选择户主文化程度',
        icon: 'none'
      });
      return false;
    }
    //电话
    if (!householder.phone) {
      wx.showToast({
        title: '请填写户主电话',
        icon: 'none'
      });
      return false;
    }
    //行政区划
    if (!householder.administrativeDivisions) {
      wx.showToast({
        title: '请选择户主行政区划',
        icon: 'none'
      });
      return false;
    }
    //备注
    // if (!householder.remark) {
    //   wx.showToast({
    //     title: '请填写户主备注',
    //     icon: 'none'
    //   });
    //   return false;
    // }
    //等级
    if (!householder.abilityLevel) {
      wx.showToast({
        title: '请选择户主等级',
        icon: 'none'
      });
      return false;
    }
    //单位
    if (!householder.workUnit) {
      wx.showToast({
        title: '请填写户主工作单位/学校',
        icon: 'none'
      });
      return false;
    }

    // 如果配偶有姓名，进行配偶相关字段验证
    const spouse = this.data.formData.spouse;
    if (spouse.name) {
      if (!spouse.idNumber) {
        wx.showToast({
          title: '请填写配偶身份证号',
          icon: 'none'
        });
        return false;
      }
      if (!reg.test(spouse.idNumber)) {
        wx.showToast({
          title: '配偶身份证号格式不正确',
          icon: 'none'
        });
        return false;
      }

      if (!spouse.phone) {
        wx.showToast({
          title: '请填写配偶电话',
          icon: 'none'
        });
        return false;
      }
      // 户籍地址
      if (!spouse.address) {
        wx.showToast({
          title: '请填写配偶户籍地址',
          icon: 'none'
        });
        return false;
      }
      if (!spouse.currentAddress) {
        wx.showToast({
          title: '请填写配偶现住地址',
          icon: 'none'
        });
        return false;
      }
      //性别
      if (!spouse.gender) {
        wx.showToast({
          title: '请选择配偶性别',
          icon: 'none'
        });
        return false;
      }
      // 出生日期
      if (!spouse.birthday) {
        wx.showToast({
          title: '请填写配偶出生日期',
          icon: 'none'
        });
        return false;
      }
      // 民族
      if (!spouse.ethnicity) {
        wx.showToast({
          title: '请选择配偶民族',
          icon: 'none'
        });
        return false;
      }
      // 地域
      if (!spouse.region) {
        wx.showToast({
          title: '请选择配偶地域',
          icon: 'none'
        });
        return false;
      }
      // 政治面貌
      if (!spouse.political) {
        wx.showToast({
          title: '请选择配偶政治面貌',
          icon: 'none'
        });
        return false;
      }
      // 婚姻状况
      if (!spouse.maritalStatus) {
        wx.showToast({
          title: '请选择配偶婚姻状况',
          icon: 'none'
        });
        return false;
      }
      // 文化程度
      if (!spouse.education) {
        wx.showToast({
          title: '请选择配偶文化程度',
          icon: 'none'
        });
        return false;
      }
      //电话
      if (!spouse.phone) {
        wx.showToast({
          title: '请填写配偶电话',
          icon: 'none'
        });
        return false;
      }
      //行政区划
      if (!spouse.administrativeDivisions) {
        wx.showToast({
          title: '请选择配偶行政区划',
          icon: 'none'
        });
        return false;
      }
      // 工作单位/学校
      if (!spouse.workUnit) {
        wx.showToast({
          title: '请填写配偶工作单位/学校',
          icon: 'none'
        });
        return false;
      }
      //备注
      // if (!spouse.remark) {
      //   wx.showToast({
      //     title: '请填写配偶备注',
      //     icon: 'none'
      //   });
      //   return false;
      // }
      //等级
      if (!spouse.abilityLevel) {
        wx.showToast({
          title: '请选择配偶等级',
          icon: 'none'
        });
        return false;
      }
    }
    //成员
    const memberList = this.data.formData.memberList;
    for (let i = 0; i < memberList.length; i++) {
      const member = memberList[i];
      //如果姓名不为空，进行验证
      if (member.name) {
        if (!member.relation) {
          wx.showToast({
            title: '请选择成员关系',
            icon: 'none'
          });
          return false;
        }
        if (!member.isAdopted) {
          wx.showToast({
            title: '请选择成员是否收养',
            icon: 'none'
          });
          return false;
        }
        if (!member.gender) {
          wx.showToast({
            title: '请选择成员性别',
            icon: 'none'
          });
          return false;
        }
        if (!member.birthday) {
          wx.showToast({
            title: '请填写成员出生日期',
            icon: 'none'
          });
          return false;
        }
        if (!member.healthStatus) {
          wx.showToast({
            title: '请选择成员健康状况',
            icon: 'none'
          });
          return false;
        }
        if (!member.selfCareAbility) {
          wx.showToast({
            title: '请选择成员自理能力',
            icon: 'none'
          });
          return false;
        }
        if (!member.isLivingAlone) {
          wx.showToast({
            title: '请选择成员是否独居',
            icon: 'none'
          });
          return false;
        }
        if (!member.hasChronicDisease) {
          wx.showToast({
            title: '请选择成员是否患有慢性病',
            icon: 'none'
          });
          return false;
        }
        if (!member.abilityLevel) {
          wx.showToast({
            title: '请选择成员等级',
            icon: 'none'
          });
          return false;
        }
      }
    }
    // 家庭等级
    if (!this.data.formData.familyLevel) {
      wx.showToast({
        title: '请选择家庭等级',
        icon: 'none'
      });
      return false;
    }
    // 年收入
    if (!this.data.formData.income) {
      wx.showToast({
        title: '请填写年收入',
        icon: 'none'
      });
      return false;
    }
    // 年支出
    if (!this.data.formData.expense) {
      wx.showToast({
        title: '请填写年支出',
        icon: 'none'
      });
    }
    //省份
    if (!this.data.formData.province) {
      wx.showToast({
        title: '请选择省份',
        icon: 'none'
      });
      return false;
    }
    //县
    if (!this.data.formData.district) {
      wx.showToast({
        title: '请选择区/县',
        icon: 'none'
      });
      return false;
    }
    //街道
    if (!this.data.formData.street) {
      wx.showToast({
        title: '请选择街道',
        icon: 'none'
      });
      return false;
    }
    return true;
  },

  // 删除图片
  deleteImage: function (e) {
    const type = e.currentTarget.dataset.type;

    wx.showModal({
      title: '提示',
      content: '确定要删除照片吗？',
      success: (res) => {
        if (res.confirm) {
          if (type === 'householder') {
            this.setData({
              'formData.householder.photoUrl': ''
            });
          } else if (type === 'spouse') {
            this.setData({
              'formData.spouse.photoUrl': ''
            });
          }

          wx.showToast({
            title: '照片已删除',
            icon: 'success',
            duration: 1500
          });
        }
      }
    });
  },

  // 选择图片
  chooseImage: function () {
    const that = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      camera: 'back',
      success: function (res) {
        try {
          // 获取图片临时路径
          const tempFilePaths = res.tempFiles[0].tempFilePath;

          // 检查文件是否存在
          wx.getFileInfo({
            filePath: tempFilePaths,
            success: function () {
              // 文件存在，根据当前激活的标签页更新对应的照片
              if (that.data.activeTab === 'household') {
                that.setData({
                  'formData.householder.photoUrl': tempFilePaths
                });
              } else if (that.data.activeTab === 'spouse') {
                that.setData({
                  'formData.spouse.photoUrl': tempFilePaths
                });
              }
            },
            fail: function (error) {
              console.error('文件不存在:', error);
              wx.showToast({
                title: '图片文件无法读取',
                icon: 'none',
                duration: 2000
              });
            }
          });
        } catch (error) {
          console.error('处理图片失败:', error);
          wx.showToast({
            title: '图片处理失败',
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: function (error) {
        console.error('选择图片失败:', error);
        wx.showToast({
          title: '选择图片失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },

  // 预览图片
  previewImage: function (e) {
    // 根据当前标签页确定要预览的图片
    let photoUrl = '';

    if (this.data.activeTab === 'household' && this.data.formData.householder.photoUrl && this.data.formData.householder.photoUrl !== '无') {
      photoUrl = this.data.formData.householder.photoUrl;
    } else if (this.data.activeTab === 'spouse' && this.data.formData.spouse.photoUrl && this.data.formData.spouse.photoUrl !== '无') {
      photoUrl = this.data.formData.spouse.photoUrl;
    }

    if (photoUrl) {
      wx.previewImage({
        urls: [photoUrl],
        current: photoUrl
      });
    }
  },

  // 处理复选框变化
  checkboxChange: function (e) {
    const field = e.currentTarget.dataset.field;
    const values = e.detail.value;
    const newData = {};
    newData[`formData.${field}`] = values;
    this.setData(newData);
  },

  /**
   * 显示评定弹窗
   */
  showEvaluationPopup: function (e) {
    const type = e.currentTarget.dataset.type || 'householder';

    // 获取当前评定对象的数据
    let currentData = {};
    if (type === 'householder') {
      if (this.data.formData.householder.abilityLevel) {
        // 如果已有评定结果，则加载之前的评定数据
        // 这里简化处理，实际可能需要从abilityLevel解析或从其他地方获取
        // 这里仅设置默认值，实际项目中可能需要更复杂的处理
      }
    } else if (type === 'spouse') {
      if (this.data.formData.spouse.abilityLevel) {
        // 如果已有评定结果，则加载之前的评定数据
        // 简化处理同上
      }
    } else if (type === 'member') {
      // 保存成员索引信息
      const index = e.currentTarget.dataset.index;
      if (index !== undefined) {
        this.setData({
          evaluationMemberIndex: index,
          evaluationMemberType: 'memberList' // 成员列表的数据字段名
        });
      }
    }

    this.setData({
      showEvaluation: true,
      evaluationType: type
    });
  },

  /**
   * 隐藏评定弹窗
   */
  hideEvaluationPopup: function () {
    this.setData({
      showEvaluation: false
    });

    // 计算能力等级评定结果
    this.calculateAbilityLevel();
  },

  /**
   * 处理评定选项变化
   */
  evaluationOptionChange: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;

    this.setData({
      [`evaluationData.${field}`]: value
    });
  },

  /**
   * 计算能力等级评定结果
   */
  calculateAbilityLevel: function () {
    const evaluationData = this.data.evaluationData;
    const evaluationType = this.data.evaluationType;
    let score = 0;

    // 计算评分
    // 每项"完全自理"0分，"部分自理"5分，"完全不能自理"10分
    for (const key in evaluationData) {
      if (evaluationData[key] === '完全自理') {
        score += 0;
      } else if (evaluationData[key] === '部分自理') {
        score += 5;
      } else if (evaluationData[key] === '完全不能自理') {
        score += 10;
      }
    }

    // 根据总分评定等级
    let abilityLevel = '';
    if (score >= 0 && score <= 10) {
      abilityLevel = '绿';
    } else if (score > 10 && score <= 25) {
      abilityLevel = '黄';
    } else if (score > 25 && score <= 40) {
      abilityLevel = '橙';
    } else {
      abilityLevel = '红';
    }

    // 更新表单数据 - 根据评定类型更新不同对象的能力等级
    if (evaluationType === 'householder') {
      this.setData({
        'formData.householder.abilityLevel': abilityLevel
      });
    } else if (evaluationType === 'spouse') {
      this.setData({
        'formData.spouse.abilityLevel': abilityLevel
      });
    } else if (evaluationType === 'member') {
      // 更新家庭成员的能力等级
      const type = this.data.evaluationMemberType || 'memberList';
      const index = this.data.evaluationMemberIndex;

      // 检查索引是否有效
      if (index !== undefined && index >= 0 && type) {
        const path = `formData.${type}[${index}].abilityLevel`;

        this.setData({
          [path]: abilityLevel
        });
      } else {
        console.error('无效的成员索引:', index, type);
      }
    }
  },

  /**
   * 加载区域数据
   */
  loadAreaData: function () {
    // console.log('加载区域数据');
    wx.showLoading({
      title: '加载区域数据...',
    });
    const rootfatherid = 5099263649039605; // 中国的fatherId
    getSubRegion(rootfatherid).then(res => {
      if (res.data && res.data.length > 0) {
        const provinces = res.data || [];
        const provinceList = provinces.map(item => item.regionName);

        this.setData({
          provinceList: provinceList,
          originProvinces: provinces
        });
      } else {
        wx.showToast({
          title: '获取区域数据失败',
          icon: 'none'
        });
      }
      wx.hideLoading();
    }).catch(err=>{
      console.error('请求区域数据失败', err);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
      wx.hideLoading();
    });
    // 请求腾讯地图行政区划接口
    // wx.request({
    //   url: 'https://apis.map.qq.com/ws/district/v1/list',
    //   data: {
    //     key: 'LXLBZ-HP66Q-PYL5K-B74JY-IFTMK-RYFV2'
    //   },
    //   success: (res) => {
    //     if (res.data && res.data.status === 0) {
    //       // 处理省级数据
    //       const provinces = res.data.result[0] || [];
    //       const provinceList = provinces.map(item => item.fullname);

    //       this.setData({
    //         provinceList,
    //         originProvinces: provinces
    //       });

    //       // console.log('省级数据加载成功', provinceList);  
    //     } else {
    //       console.error('获取区域数据失败', res);
    //       wx.showToast({
    //         title: '获取区域数据失败',
    //         icon: 'none'
    //       });
    //     }
    //     wx.hideLoading();
    //   },
    //   fail: (err) => {
    //     console.error('请求区域数据失败', err);
    //     wx.showToast({
    //       title: '网络错误，请重试',
    //       icon: 'none'
    //     });
    //     wx.hideLoading();
    //   }
    // });
  },

  /**
   * 根据省ID获取城市列表
   */
  getCityList: function (provinceId) {
    wx.showLoading({
      title: '加载城市数据...',
    });
    getSubRegion(provinceId).then(res => { 
      if(res.data&& res.data.length>0){
        const cities = res.data || [];
        const cityList = cities.map(item => item.regionName);

        this.setData({
          cityList,
          originCities: cities,
          cityIndex: 0,
          // 清空区县和街道
          districtList: [],
          streetList: [],
          districtIndex: 0,
          streetIndex: 0,
          'formData.city': '',
          'formData.district': '',
          'formData.street': '',
          directCitySelected: false
        })
      } else{
        wx.showToast({
          title: '获取城市数据失败',
          icon: 'none'
        });
      }
      wx.hideLoading();
    }).catch(err=>{
      console.error('请求城市数据失败', err);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
      wx.hideLoading();
    });
    // wx.request({
    //   url: 'https://apis.map.qq.com/ws/district/v1/getchildren',
    //   data: {
    //     key: 'LXLBZ-HP66Q-PYL5K-B74JY-IFTMK-RYFV2',
    //     id: provinceId
    //   },
    //   success: (res) => {
    //     if (res.data && res.data.status === 0) {
    //       const cities = res.data.result[0] || [];
    //       const cityList = cities.map(item => item.fullname);

    //       this.setData({
    //         cityList,
    //         originCities: cities,
    //         cityIndex: 0,
    //         // 清空区县和街道
    //         districtList: [],
    //         streetList: [],
    //         districtIndex: 0,
    //         streetIndex: 0,
    //         'formData.city': '',
    //         'formData.district': '',
    //         'formData.street': '',
    //         directCitySelected: false
    //       });

    //       // console.log('城市数据加载成功', cityList);
    //     } else {
    //       console.error('获取城市数据失败', res);
    //       wx.showToast({
    //         title: '获取城市数据失败',
    //         icon: 'none'
    //       });
    //     }
    //     wx.hideLoading();
    //   },
    //   fail: (err) => {
    //     console.error('请求城市数据失败', err);
    //     wx.showToast({
    //       title: '网络错误，请重试',
    //       icon: 'none'
    //     });
    //     wx.hideLoading();
    //   }
    // });
  },

  /**
   * 根据市ID获取区县列表
   */
  getDistrictList: function (cityId) {
    wx.showLoading({
      title: '加载区县数据...',
    });
    getSubRegion(cityId).then(res => { 
      if(res.data&& res.data.length>0){
        const districts = res.data || [];
        const districtList = districts.map(item => item.regionName);

        this.setData({
          districtList,
          originDistricts: districts,
          districtIndex: 0,
          // 清空街道
          streetList: [],
          streetIndex: 0,
          'formData.district': '',
          'formData.street': ''
        })
      } else{
        wx.showToast({
          title: '获取区县数据失败',
          icon: 'none'
        });
      }
      wx.hideLoading();
    }).catch(err=>{
      console.error('请求区县数据失败', err);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
      wx.hideLoading();
    });
    // wx.request({
    //   url: 'https://apis.map.qq.com/ws/district/v1/getchildren',
    //   data: {
    //     key: 'LXLBZ-HP66Q-PYL5K-B74JY-IFTMK-RYFV2',
    //     id: cityId
    //   },
    //   success: (res) => {
    //     if (res.data && res.data.status === 0) {
    //       const districts = res.data.result[0] || [];
    //       const districtList = districts.map(item => item.fullname);

    //       this.setData({
    //         districtList,
    //         originDistricts: districts,
    //         districtIndex: 0,
    //         // 清空街道
    //         streetList: [],
    //         streetIndex: 0,
    //         'formData.district': '',
    //         'formData.street': ''
    //       });

    //       // console.log('区县数据加载成功', districtList);
    //     } else {
    //       console.error('获取区县数据失败', res);
    //       wx.showToast({
    //         title: '获取区县数据失败',
    //         icon: 'none'
    //       });
    //     }
    //     wx.hideLoading();
    //   },
    //   fail: (err) => {
    //     console.error('请求区县数据失败', err);
    //     wx.showToast({
    //       title: '网络错误，请重试',
    //       icon: 'none'
    //     });
    //     wx.hideLoading();
    //   }
    // });
  },

  /**
   * 根据区县ID获取街道列表
   */
  getStreetList: function (districtId) {
    wx.showLoading({
      title: '加载街道数据...',
    });
    getSubRegion(districtId).then(res => { 
      if (res.data && res.data.length > 0) {
        const streets = res.data || [];
        const streetList = streets.map(item => item.regionName);

        this.setData({
          streetList,
          originStreets: streets,
          streetIndex: 0,
          'formData.street': ''
        })
      } else{
        wx.showToast({
          title: '获取街道数据失败',
          icon: 'none'
        });
      }
      wx.hideLoading();
    }).catch(err=>{
      console.error('请求街道数据失败', err);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
      wx.hideLoading();
    });
    //
    // wx.request({
    //   url: 'https://apis.map.qq.com/ws/district/v1/getchildren',
    //   data: {
    //     key: 'LXLBZ-HP66Q-PYL5K-B74JY-IFTMK-RYFV2',
    //     id: districtId
    //   },
    //   success: (res) => {
    //     if (res.data && res.data.status === 0) {
    //       const streets = res.data.result[0] || [];
    //       const streetList = streets.map(item => item.fullname);

    //       this.setData({
    //         streetList,
    //         originStreets: streets,
    //         streetIndex: 0,
    //         'formData.street': ''
    //       });

    //       // console.log('街道数据加载成功', streetList);
    //     } else {
    //       console.error('获取街道数据失败', res);
    //       wx.showToast({
    //         title: '获取街道数据失败',
    //         icon: 'none'
    //       });
    //     }
    //     wx.hideLoading();
    //   },
    //   fail: (err) => {
    //     console.error('请求街道数据失败', err);
    //     wx.showToast({
    //       title: '网络错误，请重试',
    //       icon: 'none'
    //     });
    //     wx.hideLoading();
    //   }
    // });
  },

  /**
   * 处理省份选择变化
   */
  provinceChange: function (e) {
    const index = e.detail.value;
    const province = this.data.provinceList[index];
    const provinceCode = this.data.originProvinces[index].regionCode;
    const provinceId = this.data.originProvinces[index].uid;

    // 判断是否是直辖市（北京市、天津市、上海市、重庆市）
    const directCities = ['北京市', '天津市', '上海市', '重庆市'];
    const isDirectCity = directCities.includes(province);

    this.setData({
      provinceIndex: index,
      'formData.provinceCode': provinceCode,
      'formData.province': province,
      directCitySelected: isDirectCity
    });

    if (isDirectCity) {
      // 如果是直辖市，市级自动设置为与省级相同
      this.setData({
        'formData.city': province,
        cityList: [province],
        cityIndex: 0,
        originCities: [{
          id: provinceId,
          fullname: province
        }]
      });

      // 直接加载区县列表
      this.getCityList(provinceId);
    } else {
      // 普通省份，加载选中省份的城市列表
      this.getCityList(provinceId);
    }
  },

  /**
   * 处理城市选择变化
   */
  cityChange: function (e) {
    const index = e.detail.value;
    const city = this.data.cityList[index];
    const cityCode = this.data.originCities[index].regionCode;
    const cityId = this.data.originCities[index].uid;

    this.setData({
      cityIndex: index,
      'formData.cityCode': cityCode,
      'formData.city': city
    });

    // 加载选中城市的区县列表
    this.getDistrictList(cityId);
  },

  /**
   * 处理区县选择变化
   */
  districtChange: function (e) {
    const index = e.detail.value;
    const district = this.data.districtList[index];
    const districtCode = this.data.originDistricts[index].regionCode;
    const districtId = this.data.originDistricts[index].uid;

    this.setData({
      districtIndex: index,
      'formData.districtCode': districtCode,
      'formData.district': district
    });

    // 加载选中区县的街道列表
    this.getStreetList(districtId);
  },

  /**
   * 处理街道选择变化
   */
  streetChange: function (e) {
    const index = e.detail.value;
    const street = this.data.streetList[index];
    const streetCode = this.data.originStreets[index].regionCode;
    const streetId = this.data.originStreets[index].uid;

    this.setData({
      streetIndex: index,
      'formData.streetCode': streetCode,
      'formData.street': street
    });

    // 更新行政区划数据
    const administrativeDivisions = this.data.formData.province + this.data.formData.city + this.data.formData.district + this.data.formData.street;
    this.setData({
      'formData.administrativeDivisions': administrativeDivisions
    });
  },

  /**
   * 显示家庭成员评定弹窗
   */
  showMemberEvaluationPopup: function (e) {
    const type = e.currentTarget.dataset.type; // childrenList, grandchildrenList 等
    const index = e.currentTarget.dataset.index; // 成员索引

    // 获取当前评定对象的数据
    let currentItem = this.data.formData[type][index];

    this.setData({
      showEvaluation: true,
      evaluationType: 'member',
      evaluationMemberType: type,
      evaluationMemberIndex: index
    });
  },

  /**
   * 处理户主行政区划选择器变化
   */
  householderAdminRegionChange: function (e) {
    const region = e.detail.value;
    const regionText = region[0] + region[1] + region[2];

    this.setData({
      'formData.householder.adminRegionText': regionText,
      'formData.householder.administrativeDivisions': regionText
    });
  },

  /**
   * 处理配偶行政区划选择器变化
   */
  spouseAdminRegionChange: function (e) {
    const region = e.detail.value;
    const regionText = region[0] + region[1] + region[2];

    this.setData({
      'formData.spouse.adminRegionText': regionText,
      'formData.spouse.administrativeDivisions': regionText
    });
  },

  /**
   * 显示搜索弹窗
   */
  showSearchPopup: function () {
    this.setData({
      showSearch: true,
      'searchData.name': '',
      'searchData.idNumber': '',
      'searchData.region': '',
      searchResults: [],
      searchPerformed: false
    });

    // iOS优化：防止页面滚动
    if (wx.getSystemInfoSync().platform === 'ios') {
      this.originalPageScroll = this.data.enablePageScroll;
      this.setData({
        enablePageScroll: false
      });
    }
  },

  /**
   * 隐藏搜索弹窗
   */
  hideSearchPopup: function () {
    this.setData({
      showSearch: false
    });

    // iOS优化：恢复页面滚动
    if (wx.getSystemInfoSync().platform === 'ios' && this.originalPageScroll !== undefined) {
      this.setData({
        enablePageScroll: this.originalPageScroll
      });
    }
  },

  /**
   * 处理输入框获取焦点 - iOS优化
   */
  handleInputFocus: function (e) {
    // iOS下软键盘弹起时的处理
    if (wx.getSystemInfoSync().platform === 'ios') {
      // 添加iOS键盘激活状态
      this.setData({
        iosKeyboardActive: true
      });

      // 延迟调整弹窗位置，确保软键盘已完全弹起
      setTimeout(() => {
        this.adjustPopupPosition();
      }, 300);
    }
  },

  /**
   * 处理输入框失去焦点 - iOS优化
   */
  handleInputBlur: function (e) {
    // iOS下软键盘收起时的处理
    if (wx.getSystemInfoSync().platform === 'ios') {
      // 移除iOS键盘激活状态
      this.setData({
        iosKeyboardActive: false
      });

      setTimeout(() => {
        this.resetPopupPosition();
      }, 300);
    }
  },

  /**
   * 调整弹窗位置 - iOS软键盘适配
   */
  adjustPopupPosition: function () {
    // 可以通过查询节点信息来动态调整弹窗位置
    const query = this.createSelectorQuery();
    query.select('.search-panel').boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec((res) => {
      if (res && res[0]) {
        // 根据实际需要调整弹窗位置
        // 这里可以添加具体的位置调整逻辑
      }
    });
  },

  /**
   * 重置弹窗位置
   */
  resetPopupPosition: function () {
    // 重置弹窗到默认位置
    // 通常软键盘收起后会自动恢复
  },

  /**
   * 处理搜索输入框变化
   */
  searchInputChange: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    const newData = {};
    newData[`searchData.${field}`] = value;
    this.setData(newData);
  },

  /**
   * 执行搜索
   */
  performSearch: function () {
    const data = {
      "NameKey": this.data.searchData.name,
      "IdentifacationNumber": this.data.searchData.idNumber,
      "Region": this.data.searchData.region,
      "PageIndex": 1,
      "PageSize": 4000
    }
    console.log(data);

    // 检查搜索条件
    if (!data.NameKey && !data.IdentifacationNumber && !data.Region) {
      wx.showToast({
        title: '请输入搜索条件',
        icon: 'none'
      });
      return;
    }

    // // 显示加载提示
    wx.showLoading({
      title: '搜索中...'
    });

    // 调用临时人员数据接口
    getTempPeopleList(data).then(res => {
      // console.log('搜索结果:', res);
      if (res && res.tempFamilyData.length > 0) {

        // 处理搜索结果，只保留需要的字段
        const processedResults = res.tempFamilyData.map(person => ({
          name: person.name || '',
          phoneNumber: person.phoneNumber || '',
          gender: person.gender || '',
          address: person.address || '',
          identifacationNumber: person.identifacationNumber || '',
          // 保留原始数据以备后用
          originalData: person
        }));

        this.setData({
          searchResults: processedResults,
          searchPerformed: true
        });
        //等待1秒
        setTimeout(() => {
          wx.hideLoading();
        }, 1000);

        if (processedResults.length === 0) {
          wx.showToast({
            title: '未找到匹配信息',
            icon: 'none'
          });
        }
      } else {
        this.setData({
          searchResults: [],
          searchPerformed: true
        });
        wx.showToast({
          title: '未找到匹配信息',
          icon: 'none'
        });
      }
    }).catch(err => {
      wx.hideLoading();
      console.error('搜索失败', err);
      wx.showToast({
        title: '搜索失败，请重试',
        icon: 'none'
      });

      // 设置空结果状态
      this.setData({
        searchResults: [],
        searchPerformed: true
      });
    });
  },

  /**
   * 选择搜索结果
   */
  selectSearchResult: function (e) {
    const index = e.currentTarget.dataset.index;
    const selectedPerson = this.data.searchResults[index];

    if (!selectedPerson) {
      return;
    }

    // 询问用户要填充到哪个角色
    wx.showActionSheet({
      itemList: ['填充到户主', '填充到配偶'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 填充到户主
          this.fillPersonData('householder', selectedPerson);
        } else if (res.tapIndex === 1) {
          // 填充到配偶
          this.fillPersonData('spouse', selectedPerson);
        }

        // 关闭搜索弹窗
        this.hideSearchPopup();

        // 切换到对应的标签页
        this.setData({
          activeTab: res.tapIndex === 0 ? 'household' : 'spouse'
        });
      }
    });
  },

  /**
   * 将搜索结果填充到指定角色
   */
  fillPersonData: function (role, personData) {
    const updateData = {};

    // 基本信息 - 使用实际的字段名
    updateData[`formData.${role}.name`] = personData.name || '';
    updateData[`formData.${role}.idNumber`] = personData.identifacationNumber || '';
    updateData[`formData.${role}.phone`] = personData.phoneNumber || '';
    updateData[`formData.${role}.gender`] = personData.gender || '男';

    //拆分地址
    const tempAddress = personData.address || '';
    if (tempAddress) {
      const addressArray = splitAddress(tempAddress);
      //户籍地址
      updateData[`formData.${role}.regionText`] = addressArray[0] || '';
      updateData[`formData.${role}.detailAddress`] = addressArray[1] || '';
      updateData[`formData.${role}.address`] = addressArray[0] + addressArray[1] || '';
      //现住址
      updateData[`formData.${role}.currentRegionText`] = addressArray[0] || '';
      updateData[`formData.${role}.currentDetailAddress`] = addressArray[1] || '';
      updateData[`formData.${role}.currentAddress`] = addressArray[0] + addressArray[1] || '';
      //行政区划
      updateData[`formData.${role}.adminRegionText`] = addressArray[0];
      updateData[`formData.${role}.administrativeDivisions`] = addressArray[0];
    } else {
      updateData[`formData.${role}.regionText`] = '';
      updateData[`formData.${role}.detailAddress`] = '';
      updateData[`formData.${role}.address`] = '';
      updateData[`formData.${role}.currentRegionText`] = '';
      updateData[`formData.${role}.currentDetailAddress`] = '';
      updateData[`formData.${role}.currentAddress`] = '';
      updateData[`formData.${role}.adminRegionText`] = '';
      updateData[`formData.${role}.administrativeDivisions`] = '';
    }

    // 如果有原始数据，可以填充更多字段
    if (personData.originalData) {
      const original = personData.originalData;

      // 处理出生日期
      if (original.birthDate) {
        // 转换日期格式 "1955-10-10T00:00:00" -> "1955-10-10"
        const birthDate = original.birthDate.split('T')[0];
        updateData[`formData.${role}.birthday`] = birthDate;
      }

      // 处理婚姻状况
      if (original.marryInfo) {
        updateData[`formData.${role}.maritalStatus`] = original.marryInfo;
      }

      // 设置户籍地址和现住址为相同地址
      // if (original.address) {
      //   updateData[`formData.${role}.detailAddress`] = original.address;
      //   updateData[`formData.${role}.currentAddress`] = original.address;
      //   updateData[`formData.${role}.currentDetailAddress`] = original.address;
      // }
    }

    this.setData(updateData);

    wx.showToast({
      title: '信息已填充',
      icon: 'success'
    });
  },

})